#include <header.h>


void recycle1(void *arg){
	printf("cyc1\n");
	free(arg);
}
void recycle2(void *arg){
	printf("cyc2\n");
	int *fd = (int*)arg;
	close(*fd);
}

void *run(void *arg){
	void *mem = malloc(100);
	pthread_cleanup_push(recycle1, mem);

	int fd = open("text.txt", O_CREAT | O_RDWR);
	ERROR_CHECK(fd, -1, "open");
	pthread_cleanup_push(recycle2, &fd);

	int times = 0;
	while(1){
		sleep(1);
		write(fd, "hello\n", 6);

		times++;
		if(times > 100){
			break;
		}
	}
	

	pthread_cleanup_pop(1);
	pthread_cleanup_pop(1);
	return NULL;
}


int main(int argc, char* argv[]){
	
	pthread_t son_thread_id;
	pthread_create(&son_thread_id, NULL, run, NULL);

	sleep(8);
	pthread_cancel(son_thread_id);

	pthread_join(son_thread_id, NULL);
	return 0;
}